/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.permission.handler;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;

import com.legendshop.framework.model.GrantedFunction;
import com.legendshop.oa.constants.RoleEnum;
import com.legendshop.oa.handler.SecurityHandler;
import com.legendshop.oa.model.Function;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.permission.service.FunctionService;
import com.legendshop.util.AppUtils;

/**
 * 根据用户角色， 过滤后台资源链接.
 * 后端使用
 */
public class SecurityResourceFilterHandler implements SecurityHandler {
	/** The log. */
	private final Logger log = LoggerFactory.getLogger(SecurityResourceFilterHandler.class);
	
	/** The function service. */
	private FunctionService functionService;

	/**
	 * 检查用户是否有权限访问特定的url
	 */
	public boolean handle(HttpServletRequest request) {
		String path = request.getServletPath();
		//检查是否后台
		boolean hasAccessRight = true;
		
		// 判断是否登录
		UserDetail userDetail = UserManager.getUser(request.getSession());
			Collection<GrantedAuthority> grantedAuthorities = userDetail.getAuthorities();
			boolean contain = containRoleSupervisor(grantedAuthorities);
			if (!contain) { // 是否包含超级管理员权限
				List<Function> resourceFunction = functionService.getFunctionsByUrl(path);
				if (AppUtils.isNotBlank(resourceFunction)) {
					// 说明该URL有关联权限
					 Collection<GrantedFunction> userAuthentication = userDetail.getFunctions();
					if (AppUtils.isNotBlank(userAuthentication)) {
						hasAccessRight = checkPath(resourceFunction, userAuthentication);
					}else{
						hasAccessRight = false;
					}
				}
		}
			
		if(!hasAccessRight){
			log.warn("User {} not right to access path {}", userDetail.getUsername(), path);
		}
		return hasAccessRight;
	}
	
	private boolean checkPath(List<Function> resourceFunction, Collection<GrantedFunction> userAuthentication){
		for (int i = 0; i < resourceFunction.size(); i++) {
			String func=resourceFunction.get(i).getProtectFunction();
			if(containsAuthentication(userAuthentication,func)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断是否超级管理员帐号.
	 *
	 * @param rolesCollection the roles collection
	 * @return true, if successful
	 */
	private boolean containRoleSupervisor(Collection<GrantedAuthority> rolesCollection) {
		boolean contain = false;
		for (Iterator<GrantedAuthority> iterator = rolesCollection.iterator(); iterator.hasNext();) {
			GrantedAuthority grantedAuthority = (GrantedAuthority) iterator.next();
			if (grantedAuthority.getAuthority().equals(String.valueOf(RoleEnum.ROLE_SUPERVISOR))) {
				contain = true;
				break;
			}
		}
		return contain;
	}


	/**
	 * 判断是否包含该资源的权限信息.
	 *
	 * @param userAuthentication the user authentication
	 * @param func the func
	 * @return true, if successful
	 */
	private boolean containsAuthentication(Collection<GrantedFunction> userAuthentication, String func) {
		boolean result=false;
		for (Iterator<GrantedFunction> iterator = userAuthentication.iterator(); iterator.hasNext();) {
			GrantedFunction grantedFunction = (GrantedFunction) iterator.next();
			String function=grantedFunction.getFunction();
			if(function.equals(func)){
				result=true;
				break;
			}
		}
		return result;
	}


	/**
	 * Sets the function service.
	 *
	 * @param functionService the new function service
	 */
	public void setFunctionService(FunctionService functionService) {
		this.functionService = functionService;
	}

}
